package com.lanou.wuyou.gift.tools;

import android.os.Handler;
import android.os.Message;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by dllo on 17/3/14.
 */

public class NetWorkInstance {

    private static NetWorkInstance netWorkInstance;
    private final OkHttpClient okHttpClient;

    //1.控制好"new 构造方法"
    private NetWorkInstance() {
        super();
        okHttpClient = new OkHttpClient();
    }

    //2.提供一个让别人访问的方法
    public static NetWorkInstance getInstance() {
        //如果没有对象,则需要new一个
        //如果有对象了,直接返回该对象
        if (netWorkInstance == null) {
            synchronized (NetWorkInstance.class) {
                if (netWorkInstance == null) {
                    netWorkInstance = new NetWorkInstance();
                }
            }
        }

        return netWorkInstance;
    }
    //自定义方法
    //网络请求的功能方法
    public void netRequest(final String urlStr, final NetResultInterface netResultInterface){
        final Handler handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {

                switch (msg.what){
                    case 101:
                        netResultInterface.fail("fail");
                    break;
                    case 102:
                        netResultInterface.success((String)msg.obj);
                    break;
                }
                return false;
            }
        });
        //开启分支线程进行网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                Request request = new Request.Builder()
                        .url(urlStr)
                        .build();
                okHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    //请求失败
                    public void onFailure(Call call, IOException e) {

                        handler.sendEmptyMessage(101);
                    }

                    @Override
                    //请求有响应
                    public void onResponse(Call call, Response response) throws IOException {

                        Message msg = Message.obtain();
                        msg.what = 102;
                        msg.obj = response.body().string();
                        handler.sendMessage(msg);
                    }
                });
            }
        }).start();
    }
}
